import os
import urllib.request
import json5
import json
from pathlib import Path
import re

APP_SCOPE_APP_JSON = '/AppScope/app.json5'
APP_SCOPE_STRING_JSON = '/AppScope/resources/base/element/string.json'

HVIGOR_FILE = 'hvigorfile.ts'

ENTRY_MODULE_JSON = '/entry/src/main/module.json5'
ENTRY_MODULE_STRING_JSON = '/entry/src/main/resources/base/element/string.json'
ENTRY_MODULE_CN_STRING_JSON = '/entry/src/main/resources/zh_CN/element/'
ENTRY_MODULE_US_STRING_JSON = '/entry/src/main/resources/en_US/element/'

ENTRY_MODULE_PREFIX_STRING_JSON = 'string.json'

APP_ICON_BACK_GROUND_NAME = 'geely_app_back_ground'
APP_ICON_FORE_GROUND_NAME = 'geely_app_fore_ground'

APP_SCOPE_ICON_MEDIA = '/AppScope/resources/base/media/'

ENTRY_MODULE_ICON_MEDIA = '/entry/src/main/resources/base/media/'
APP_ICON_FILE_TYPE = '.png'
APP_ICON_MERGE_NAME = 'geely_app_layered_image'
APP_ICON_MERGE_TYPE = '.json'

APP_ICON = f"$media:{APP_ICON_MERGE_NAME}"

APP_ICON_TEMPLATE = {
  "layered-image":
  {
    "background" : f"$media:{APP_ICON_BACK_GROUND_NAME}",
    "foreground" : f"$media:{APP_ICON_FORE_GROUND_NAME}"
  }
}


def changeAppNameVersionCodeVersionName(projectPath, versionCode, versionName, appNameCN, appNameUS, bundleId):
    changeAppScopeInfo(projectPath, bundleId, versionCode, versionName, appNameCN, None, None)
    changeEntryInfo(projectPath, appNameCN, appNameUS,None, None)
    changeHvigorFile(projectPath,versionCode)

def changeBasicInfo(projectPath, bundleId, versionCode, versionName, appNameCN,appNameUS, appBackground, appForeground):
     changeAppScopeInfo(projectPath, bundleId, versionCode, versionName, appNameCN, appBackground, appForeground)
     changeEntryInfo(projectPath, appNameCN, appNameUS, appBackground, appForeground)
     changeHvigorFile(projectPath, versionCode)

def changeHvigorFile(projectPath,versionCode):
    with open(f"{projectPath}/{HVIGOR_FILE}", 'r', encoding='utf-8') as f:
        data = f.read()
        updated_data = matchingHandle('updateVersionCode',data,versionCode)
        if updated_data is not None:
            print(f"HvigorFile:\n{updated_data}")
            with open(f"{projectPath}/{HVIGOR_FILE}",'w', encoding='utf-8') as f:
                f.write(updated_data)

def matchingHandle(keyword,content,v):
    pattern = f'({keyword}\s*:\s*)\d+'
    match = re.search(pattern, content)
    updated_data = None
    if match:
        print(f"找到匹配项: {match.group()}")
        updated_data = re.sub(
            pattern,
            f'{keyword}:{v}',
            content
        )
    else:
        print("未找到匹配项")
    return updated_data

def changeAppScopeInfo(projectPath, bundleId, versionCode, versionName, appName,appBackground, appForeground):
    with open(f"{projectPath}{APP_SCOPE_APP_JSON}", 'r', encoding='utf-8') as f:
        data = json5.load(f)
    print(data)
    # buildId
    if bundleId != '' and not bundleId is None:
        data['app']['bundleName'] = bundleId
    # versionCode
    data['app']['versionCode'] = int(versionCode)
    # versionName
    data['app']['versionName'] = versionName
    try:
        if not appBackground is None and not appForeground is None:
            downloadImage(appBackground,
                      f"{projectPath}{APP_SCOPE_ICON_MEDIA}{APP_ICON_BACK_GROUND_NAME}{APP_ICON_FILE_TYPE}")
            downloadImage(appForeground,
                          f"{projectPath}{APP_SCOPE_ICON_MEDIA}{APP_ICON_FORE_GROUND_NAME}{APP_ICON_FILE_TYPE}")
            saveAppIconFile(f"{projectPath}{APP_SCOPE_ICON_MEDIA}{APP_ICON_MERGE_NAME}{APP_ICON_MERGE_TYPE}")
            data['app']['icon'] = APP_ICON
    except Exception as e:
        print(f"应用图标替换错误：{e}")
    changeAppName(f"{projectPath}{APP_SCOPE_STRING_JSON}", data['app']['label'], appName)
    with open(f"{projectPath}{APP_SCOPE_APP_JSON}", 'w', encoding='utf-8') as f:
        json.dump(data, f, indent=2, ensure_ascii=False)
def changeEntryInfo(projectPath, appNameCN,appNameUS,appBackground, appForeground):
    with open(f"{projectPath}{ENTRY_MODULE_JSON}", 'r', encoding='utf-8') as f:
        data = json5.load(f)
    print(f"changeEntryInfo:{data}")
    for item in  data['module']['abilities']:
        if item['name'] == 'EntryAbility':
          if appNameCN:
            changeAppName(f"{projectPath}{ENTRY_MODULE_STRING_JSON}", item['label'], appNameCN)
          try:
            if appNameCN:
                # 修改中文名称
                cn_path = f"{projectPath}{ENTRY_MODULE_CN_STRING_JSON}"
                if os.path.exists( cn_path):
                    fileName = hasFilesWithPrefix(cn_path,ENTRY_MODULE_PREFIX_STRING_JSON)
                    if not fileName is None:
                        changeAppName(f"{cn_path}{fileName}", item['label'], appNameCN)
                        print(f'中文文件名称：{cn_path}{fileName}')

            if appNameUS:
                # 修改英文名称
                us_path = f"{projectPath}{ENTRY_MODULE_US_STRING_JSON}"
                if os.path.exists(us_path):
                    fileName = hasFilesWithPrefix(us_path, ENTRY_MODULE_PREFIX_STRING_JSON)
                    if not fileName is None:
                        changeAppName(f"{us_path}{fileName}", item['label'], appNameUS)
                        print(f'英文文件名称：{us_path}{fileName}')

          except Exception as e:
              print(f"：不需要国际化")
          try:
              if not appBackground is None and not appForeground is None:
                downloadImage(appBackground,
                            f"{projectPath}{ENTRY_MODULE_ICON_MEDIA}{APP_ICON_BACK_GROUND_NAME}{APP_ICON_FILE_TYPE}")
                downloadImage(appForeground,
                            f"{projectPath}{ENTRY_MODULE_ICON_MEDIA}{APP_ICON_FORE_GROUND_NAME}{APP_ICON_FILE_TYPE}")
                saveAppIconFile(f"{projectPath}{ENTRY_MODULE_ICON_MEDIA}{APP_ICON_MERGE_NAME}{APP_ICON_MERGE_TYPE}")
                item['icon'] = APP_ICON
                print(f"changeEntryInfo:item:{item}")
          except Exception as e:
              print(f"应用图标替换错误：{e}")
    with open(f"{projectPath}{ENTRY_MODULE_JSON}", 'w', encoding='utf-8') as f:
        json.dump(data, f, indent=2, ensure_ascii=False)

def hasFilesWithPrefix(directory, prefix):
    for filename in os.listdir(directory):
        if filename.index(prefix) > 0:
            return filename
        # if filename prefix:
        #     return filename
    return None

def changeAppName(path, label, appName):
    with open(f"{path}", 'r', encoding='utf-8') as f:
        data = json5.load(f)
        label = label.replace('$', '')
        parameter = label.split(':')
    for item in data[parameter[0]]:
        if item['name'] == parameter[1]:
            item['value'] = appName
            print(item['name'])
    print(f"changeAppName:{data['string']}")
    with open(f"{path}", 'w', encoding='utf-8') as f:
        json.dump(data, f, indent=2, ensure_ascii=False)

def downloadImage(url, savePath):
    try:
        save_dir = os.path.dirname(savePath)
        if not os.path.exists(save_dir):
            os.makedirs(save_dir)
        response = urllib.request.urlopen(url)
        if response.getcode() == 200:
            with open(savePath, 'wb') as f:
                f.write(response.read())
            print(f"图片已成功保存到：{savePath}")
        else:
            print(f"无法下载图片，HTTP状态码：{response.getcode()}")
    except Exception as e:
        print(f"下载图片时发生错误：{e}")

def saveAppIconFile(savePath):
    try:
        print(savePath)
        save_dir = os.path.dirname(savePath)
        if not os.path.exists(save_dir):
            os.makedirs(save_dir)
        else:
            print(f"文件存在")
        print(APP_ICON_TEMPLATE)
        with open(f"{savePath}", 'w', encoding='utf-8') as f:
         json.dump(APP_ICON_TEMPLATE, f, indent=2, ensure_ascii=False)

    except Exception as e:
        print(f"保存应用图标错误：{e}")


MODULE_OH_PACKAGE_JSON = '/oh-package.json5'
MODULE_SRC_MAIN_MODULE_JSON = '/src/main/module.json5'
def changeModuleBasicInfo(projectPath, moduleFileName, name, version, author):
    changeModuleInfo(projectPath,moduleFileName, name, version, author)
def changeModuleInfo(projectPath, moduleFileName, name, version, author):
    if not moduleFileName is None:
        print(f"-m:模块名称：{moduleFileName}")
        projectPath = f"{projectPath}/{moduleFileName}"
        print(f"-m:模块目录：{projectPath}")
        if Path(projectPath).exists():
            with open(f"{projectPath}{MODULE_OH_PACKAGE_JSON}", 'r', encoding='utf-8') as f:
                data = json5.load(f)
                print(data)
                data['name'] = name
                data['version'] = version
                data['author'] = author
                with open(f"{projectPath}{MODULE_OH_PACKAGE_JSON}", 'w', encoding='utf-8') as f:
                    json.dump(data, f, indent=2, ensure_ascii=False)
        else:
            print("-m:模块文件不存在{moduleFileName}")
            exit(0)
    else:
        print("-m模块文件名称不能为空")
        exit(0)
def getModuleName(projectPath, moduleFileName):
    if not moduleFileName is None:
        print(f"-gmn:模块名称：{moduleFileName}")
        projectPath = f"{projectPath}/{moduleFileName}"
        print(f"-gmn:模块目录：{projectPath}")
        if Path(projectPath).exists():
            with open(f"{projectPath}{MODULE_SRC_MAIN_MODULE_JSON}", 'r', encoding='utf-8') as f:
                data = json5.load(f)
                print(f"getModuleName={data['module']['name']}")
        else:
            print(f"-gmn:模块文件不存在{moduleFileName}")
            exit(0)
    else:
        print("-gmn:模块文件名称不能为空")
        exit(0)

def getModuleType(projectPath, moduleFileName):
    if not moduleFileName is None:
        print(f"-gmt:模块名称：{moduleFileName}")
        projectPath = f"{projectPath}/{moduleFileName}"
        print(f"-gmt:模块目录：{projectPath}")
        if Path(projectPath).exists():
            with open(f"{projectPath}{MODULE_SRC_MAIN_MODULE_JSON}", 'r', encoding='utf-8') as f:
                data = json5.load(f)
                type = data['module']['type']
                if type == 'har':
                    print("getModuleType=assembleHar")
                elif type == 'shared':
                    print("getModuleType=assembleHsp")
                else:
                    print("getModuleType=assembleHar")
        else:
            print(f"-gmt:模块文件不存在{moduleFileName}")
            exit(0)
    else:
        print("-gmt:模块文件名称不能为空")
        exit(0)